package com.example.lib5.hashTab.test.testE;

public class HashTabDemoE {

    public static void main(String[] args) {
        HashTab hashTab = new HashTab(7);
        hashTab.add(new Role(123,"唐三"));
        hashTab.add(new Role(143,"唐三"));
        hashTab.add(new Role(153,"唐三"));
        hashTab.add(new Role(113,"唐三"));
        hashTab.add(new Role(163,"唐三"));
        hashTab.list();
    }
}
//节点
class Role {
    public int id;
    public String name;
    public Role next;

    public Role(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Role{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

//链表
class LinkedList{
    Role head;
    //add
    public void add(Role role){
        //如果为空的话就直接添加
        if (head==null) {
            head=role;
            return;
        }
        Role temp=role;
        while (true) {
            if (temp.next==null) {
                break;
            }
            temp=temp.next;
        }
        temp.next=role;
    }

    public void list(int i) {
        //判断链表是否为空，如果为空的话，就无需遍历
        if (head==null) {
            System.out.println(i+"链表为空");
            return;
        }
        //链表如果不为空的话，就遍历
        Role temp=head;
        while (true) {
            System.out.println(i+temp.toString());
            if (temp.next==null) {
                break;
            }
            temp=temp.next;
        }
    }

}

//哈数表
class HashTab {

    private int size;
    private LinkedList[] linkedLists;
    public HashTab(int size) {
        this.size=size;
        linkedLists=new LinkedList[size];
        for (int i = 0; i < linkedLists.length; i++) {
            linkedLists[i]=new LinkedList();
        }

    }

    public void add(Role role) {
        LinkedList linkedList = linkedLists[getHashCode(role.id)];
        linkedList.add(role);
    }

    private int  getHashCode(int id) {
        return id%size;
    }

    public void list() {
        for (int i = 0; i < linkedLists.length; i++) {
            linkedLists[i].list(i);
        }
    }
}
